package com.easy.work.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Looper;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.base.syslib.util.MessageTools;
import com.easy.work.app.CommonValue;
import com.easy.work.oss.OssService;
import com.easy.work.oss.PauseableUploadRequest;
import com.easy.work.oss.PauseableUploadResult;
import com.easy.work.oss.PauseableUploadTask;
import com.easy.work.oss.ProgressInputStream;
import com.easy.work.oss.UICallback;
import com.easy.work.oss.UIProgressCallback;
import com.easy.work.oss.ImageDisplayer;
import com.easy.work.oss.UIDispatcher;

import java.io.IOException;
import java.io.InputStream;

public class UserOssUtils {

    private static final String accessKeyId = "LTAILpv5qAWWrb78";
    private static final String accessKeySecret = "oCS1pQg2n3D7bhu6pcaltjgkrB68KZ";

    private String bucket = "easywork";
    // endpoint以杭州为例，其它region请按实际情况填写
    private final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    //    private final String callbackAddress = "http://oss-demo.aliyuncs.com:23450";
    public static String uploadUrl = "http://easywork.oss-cn-beijing.aliyuncs.com/";
//    public static String uploadUrl = "http://easywork.oss-cn-beijing.aliyuncs.com/user/";
    // private String stsServer ;

    // 负责所有的界面更新
    public ImageDisplayer ImageDisplayer;
    public UIDispatcher UIDispatcher;
    private Context context;
    // private ImageView upload_image;
    public OssService ossService;

    private int pauseTaskStatus;
    private PauseableUploadTask task;
    private String pauseObject;
    private String pauseLocalFile;


    // public interface upLoadCallback
    // {
    // abstract void onSuccess( String url );
    //
    //
    // abstract void onFailure( String message );
    //
    // }
    //

    public UserOssUtils(Context context, String stsServer) {

        // TODO Auto-generated constructor stub

        this.context = context;
        // this.stsServer = stsServer;

    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public static String getUploadUrl() {
        return uploadUrl;
    }

    public static void setUploadUrl(String uploadUrl) {
        UserOssUtils.uploadUrl = uploadUrl;
    }


    public String getimg_url(String objectKey) {

        return ossService.getimg_url(bucket, objectKey);
    }


    // 初始化一个OssService用来上传下载
    public OssService initOSS(String endpoint, String bucket, ImageDisplayer displayer) {

        // 如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        // 使用自己的获取STSToken的类
        // OSSCredentialProvider credentialProvider = new STSGetter(stsServer);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(context, endpoint, credentialProvider, conf);
        return new OssService(oss, bucket, displayer);
    }


    public void initOssData() {

        ImageView imageView = new ImageView(context);
        imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        ImageDisplayer = new ImageDisplayer(imageView);
        UIDispatcher = new UIDispatcher(Looper.getMainLooper());
        ossService = initOSS(endpoint, bucket, ImageDisplayer);
        // 设置上传的callback地址，目前暂时只支持putObject的回调
//        ossService.setCallbackAddress(callbackAddress);

    }


    public void initOssData(ImageView imageView) {

        ImageDisplayer = new ImageDisplayer(imageView);
        UIDispatcher = new UIDispatcher(Looper.getMainLooper());
        ossService = initOSS(endpoint, bucket, ImageDisplayer);
        // 设置上传的callback地址，目前暂时只支持putObject的回调
//        ossService.setCallbackAddress(callbackAddress);

    }


    public void displayToast(String info) {
        MessageTools.showToast(context, info);
    }


    public void displayDialog(String title, String message) {

        new AlertDialog.Builder(context).setTitle(title).setMessage(message).show();
    }


    // 进度条加载回调（未使用）
    public class ProgressCallbackFactory<T> {

        public UIProgressCallback<T> get() {

            return new UIProgressCallback<T>(UIDispatcher) {

                @Override
                public void onProgress(T request, long currentSize, long totalSize) {

                    final int progress = (int) (100 * currentSize / totalSize);
                    addCallback(new Runnable() {

                        @Override
                        public void run() {

                            // updateProgress(progress);
                            // displayInfo("进度: " + String.valueOf(progress) +
                            // "%");
                        }
                    });
                    super.onProgress(request, currentSize, totalSize);
                }
            };
        }
    }


    // 下载回调
    public UICallback<GetObjectRequest, GetObjectResult> getGetCallback() {

        return new UICallback<GetObjectRequest, GetObjectResult>(UIDispatcher) {

            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {

                // 请求成功
                InputStream inputStream = result.getObjectContent();
                // 重载InputStream来获取读取进度信息
                ProgressInputStream progressStream = new ProgressInputStream(inputStream,
                        new ProgressCallbackFactory<GetObjectRequest>().get(), result.getContentLength());
                try {
                    // 需要根据对应的View大小来自适应缩放
                    final Bitmap bm = ImageDisplayer.autoResizeFromStream(progressStream);
                    final String object = request.getObjectKey();
                    final String requestid = result.getRequestId();
                    // addCallback( new Runnable() {
                    //
                    // @Override
                    // public void run() {
                    //
                    // // displayImage(bm);
                    // //displayToast( "下载成功" );
                    // //
                    // displayInfo(String.format("Bucket: %s\nObject: %s\nRequestId: %s",
                    // // bucket,
                    // // object,
                    // // requestid));
                    // }
                    // }, null );
                    super.onSuccess(request, result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {

                String info = "";
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);
                addCallback(null, new Runnable() {

                    @Override
                    public void run() {

                        displayDialog("下载失败", outputinfo);
                        // displayInfo(outputinfo);
                    }
                });
                super.onFailure(request, clientExcepion, serviceException);
            }
        };
    }


    // 普通上传回调
    public UICallback<PutObjectRequest, PutObjectResult> getPutCallback() {

        return new UICallback<PutObjectRequest, PutObjectResult>(UIDispatcher) {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Log.d("PutObject", "UploadSuccess");

                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                final String object = request.getObjectKey();
                final String ETag = result.getETag();
                final String requestid = result.getRequestId();
                final String callback = result.getServerCallbackReturnBody();

                addCallback(new Runnable() {

                    @Override
                    public void run() {

                        // displayToast( "上传成功" );
                        // String url = getimg_url( object );
                        // displayInfo(String.format("Bucket: %s\nObject: %s\nETag: %s\nRequestId: %s\nCallback: %s",
                        // bucket,
                        // object,
                        // ETag,
                        // requestid,
                        // callback));
                    }
                }, null);
                super.onSuccess(request, result);
            }


            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {

                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);
                addCallback(null, new Runnable() {

                    @Override
                    public void run() {

                        displayDialog("上传失败", outputinfo);
                        // displayInfo(outputinfo);
                    }
                });
                onFailure(request, clientExcepion, serviceException);
            }
        };
    }


    // 断点上传回调（未使用）
    public UICallback<PauseableUploadRequest, PauseableUploadResult> getMultiPartCallback() {

        return new UICallback<PauseableUploadRequest, PauseableUploadResult>(UIDispatcher) {

            // 上传成功
            @Override
            public void onSuccess(PauseableUploadRequest request, PauseableUploadResult result) {

                Log.d("PutObject", "UploadSuccess");

                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                final String object = request.getObjectKey();
                final String ETag = result.getETag();
                final String requestid = result.getRequestId();

                addCallback(new Runnable() {

                    @Override
                    public void run() {

                        displayToast("断点上传成功");
                        // displayInfo("Bucket: " + bucket + "\nObject: " +
                        // object + "\nETag: " + ETag + "\nRequestId: " +
                        // requestid);
                    }
                }, null);
                super.onSuccess(request, result);
            }


            // 上传失败
            @Override
            public void onFailure(PauseableUploadRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {

                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);
                addCallback(null, new Runnable() {

                    @Override
                    public void run() {

                        displayDialog("上传失败", outputinfo);
                        // displayInfo(outputinfo);
                    }
                });
                super.onFailure(request, clientExcepion, serviceException);
            }
        };
    }


    // 断点上传调用方法（未使用）
    public void anscyTaskPUpload(String objectName, String picturePath) {

        task = ossService.asyncMultiPartUpload(objectName, picturePath,
                getMultiPartCallback().addCallback(new Runnable() {

                    @Override
                    public void run() {

                        pauseTaskStatus = CommonValue.TASK_NONE;
                        task = null;
                    }
                }), new ProgressCallbackFactory<PauseableUploadRequest>().get());
        pauseTaskStatus = CommonValue.TASK_RUNNING;
        pauseObject = objectName;
        pauseLocalFile = picturePath;
    }


    // 普通上传调用方法
    public void anscyTaskUpload(String objectName, String picturePath) {

        String objName = "chatimage/" + objectName;
        ossService.asyncPutImage(objName, picturePath, getPutCallback(),
                new ProgressCallbackFactory<PutObjectRequest>().get());
    }


    /**
     * 普通上传调用方法 (这里描述这个方法适用条件 – 可选)
     *
     * @param objectName  生成字符串，作为保存到服务器的名字
     * @param picturePath 本地的图片地址
     * @param callback    void
     * @throws
     * @since 1.0.0
     */
    public void asyncTaskUpload(String objectName, String picturePath,
                                UICallback<PutObjectRequest, PutObjectResult> callback) {

        ossService
                .asyncPutImage(objectName, picturePath, callback, new ProgressCallbackFactory<PutObjectRequest>().get());
    }


    // 下载调用方法
    public void asyncDownload(String objectName) {

//        String objName = "chatimage/" + objectName;
        ossService.asyncGetImage(objectName, getGetCallback());
    }


    public void asyncDownload(String objectName, UICallback<GetObjectRequest, GetObjectResult> callback) {

//        String objName = "chatimage/" + objectName;
        ossService.asyncGetImage(objectName, callback);
    }
}
